<template>
	<div>
		<main-content
			:tableHeight.sync="tableHeight"
			:otherDependenComponents="otherDependenComponents"
		>
			<template slot="query">
				<el-form
					ref="form"
					:inline="true"
					:model="queryData"
					label-width="auto"
					class="flex-warp-container"
				>
					<el-form-item
						label="所属商户:"
						class="flex-row-container"
						label-width="77px"
					>
						<merchant-select
							v-model="queryData.merchantId"
							placeholder="默认选择全部"
						></merchant-select>
					</el-form-item>
					<el-form-item
						:label="`代理账号:`"
						class="flex-row-container"
						label-width="77px"
					>
						<el-input
							v-model="queryData.proxyName"
							class="input-with-select"
							:placeholder="$t('common.please_enter')"
							clearable
							size="medium"
							v-input="{ name: 'num_alp' }"
						></el-input>
					</el-form-item>

					<el-form-item
						:label="
							`${$t('funds.fund_audit.parent_proxy_account')}:`
						"
						class="flex-row-container"
						disabled
						label-width="77px"
					>
						<el-input
							v-model="queryData.parentProxyName"
							class="input-with-select"
							:placeholder="$t('common.please_enter')"
							clearable
							size="medium"
							v-input="{ name: 'num_alp' }"
						></el-input>
					</el-form-item>
					<el-form-item
						:label="
							`${$t('funds.fund_audit.belong_general_agent')}:`
						"
						class="flex-row-container"
						label-width="77px"
					>
						<el-input
							v-model="queryData.topProxyName"
							class="input-with-select"
							:placeholder="$t('common.please_enter')"
							clearable
							size="medium"
							v-input="{ name: 'num_alp' }"
						></el-input>
					</el-form-item>
					<el-form-item
						:label="`业务模式:`"
						class="flex-row-container"
						label-width="77px"
					>
						<business-model-selector
							v-model="queryData.businessModel"
						/>
					</el-form-item>

					<el-form-item style="margin-left: 8px">
						<el-button
							type="primary"
							icon="el-icon-search"
							:disabled="loading"
							size="medium"
							@click="search"
						>
							{{ $t('common.search') }}
						</el-button>
						<el-button
							icon="el-icon-refresh-left"
							:disabled="loading"
							size="medium"
							@click="reset"
						>
							{{ $t('common.reset') }}
						</el-button>
						<el-button
							icon="el-icon-plus"
							v-if="hasPermission('90870080')"
							type="warning"
							size="medium"
							@click="addFn"
						>
							新增
						</el-button>
						<el-button
							size="medium"
							v-if="hasPermission('90870083')"
							type="warning"
							@click="allocationFn(2)"
						>
							信用线默认配置
						</el-button>
						<el-button
							size="medium"
							v-if="hasPermission('90870084')"
							type="warning"
							@click="allocationFn(1)"
						>
							现金线默认配置
						</el-button>
					</el-form-item>
				</el-form>
			</template>
			<template slot="content">
				<el-table
					v-loading="loading"
					element-loading-spinner="el-icon-loading"
					border
					size="mini"
					class="small-size-table"
					:data="dataList"
					:max-height="tableHeight"
					highlight-current-row
					style="width: 100%"
					:header-cell-style="getRowClass"
				>
					<el-table-column
						width="200px"
						prop="sort"
						align="center"
						:label="`代理账号`"
					>
						<template slot-scope="scope">
							{{ scope.row.proxyName || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						width="200px"
						prop="sort"
						align="center"
						:label="`直属上级`"
					>
						<template slot-scope="scope">
							{{ scope.row.parentProxyName || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						width="200px"
						prop="sort"
						align="center"
						:label="`所属总代`"
					>
						<template slot-scope="scope">
							{{ scope.row.topProxyName || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						width="200px"
						prop="sort"
						align="center"
						:label="`所属商户`"
					>
						<template slot-scope="scope">
							{{ scope.row.merchantName || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						width="200px"
						prop="sort"
						align="center"
						:label="`业务模式`"
					>
						<template slot-scope="scope">
							{{
								mappingBusinessModels(
									scope.row.businessModel
								) || '-'
							}}
						</template>
					</el-table-column>

					<el-table-column
						prop="appDownloadConfig"
						width="200px"
						align="center"
						:label="'下载APP入口开关'"
					>
						<template slot-scope="scope">
							<!-- :disabled="!hasPermission('403011')" -->
							<el-switch
								:value="scope.row.appDownloadConfig"
								:active-value="1"
								:disabled="!hasPermission('90870085')"
								:inactive-value="0"
								@change="
									updatedStatus(
										scope.row,
										'appDownloadConfig'
									)
								"
							/>
						</template>
					</el-table-column>

					<el-table-column
						prop="createdBy"
						align="center"
						width="200px"
						:label="'创建人'"
						show-overflow-tooltip
					>
						<template slot-scope="scope">
							{{ scope.row.createdBy || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						prop="createdAt"
						align="center"
						width="200px"
						:label="'创建时间'"
						show-overflow-tooltip
					>
						<template slot-scope="scope">
							{{ scope.row.createdAt || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						prop="updatedBy"
						align="center"
						width="200px"
						:label="'最后操作人'"
						show-overflow-tooltip
					>
						<template slot-scope="scope">
							{{ scope.row.updatedBy || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						prop="updatedAt"
						width="200px"
						align="center"
						:label="'最后操作时间'"
						show-overflow-tooltip
					>
						<template slot-scope="scope">
							{{ scope.row.updatedAt || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						prop="auditStep"
						width="200px"
						align="center"
						:label="$t('common.actions')"
						fixed="right"
					>
						<template slot-scope="scope">
							<el-button
								v-if="hasPermission('90870081')"
								type="primary"
								size="medium"
								@click="openEditDialog(scope.row)"
							>
								{{ $t('common.edit') }}
							</el-button>
							<el-button
								v-if="hasPermission('90870082')"
								type="primary"
								class="action-button"
								@click="handleDelete(scope.row)"
							>
								{{ $t('common.delete') }}
							</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页 -->
				<el-pagination
					:current-page.sync="pageNum"
					class="pageValue"
					background
					layout="total, sizes,prev, pager, next, jumper"
					:page-size="queryData.pageSize"
					:page-sizes="pageSizes"
					:total="total"
					:pager-count="9"
					@current-change="handleCurrentChange"
					@size-change="handleSizeChange"
				></el-pagination>
			</template>
			<el-dialog
				:visible.sync="visibleDialog"
				:title="ruleFormType === 'edit' ? '编辑' : `新增`"
				:width="getWidth('500px')"
			>
				<el-form
					ref="dialogFormRef"
					:model="formData"
					:rules="editFormRules"
					:close-on-click-modal="false"
				>
					<el-form-item
						label-width="100px"
						:label="`所属商户:`"
						prop="merchantId"
					>
						<merchant-select
							v-if="ruleFormType === 'add'"
							style="width: 280px"
							v-model="formData.merchantId"
							placeholder="默认选择全部"
						></merchant-select>
						<span v-else>{{ formData.merchantName }}</span>
					</el-form-item>
					<el-form-item
						label-width="100px"
						:label="`代理账号:`"
						prop="proxyName"
					>
						<el-input
							v-if="ruleFormType === 'add'"
							:disabled="!formData.merchantId"
							v-model="formData.proxyName"
							@blur="getBusinessModel"
							style="width: 280px"
							:placeholder="'请输入'"
							v-input="{ name: 'num_alp' }"
						></el-input>
						<span v-else>{{ formData.proxyName }}</span>
					</el-form-item>
					<el-form-item
						prop="businessModel"
						label-width="100px"
						:label="$t('common.business_model') + ':'"
						:placeholder="$t('common.business_choose_default')"
					>
						<business-model-selector
							style="width: 280px"
							disabled
							v-if="ruleFormType === 'add'"
							v-model="formData.businessModel"
						/>
						<span v-else>
							{{ mappingBusinessModels(formData.businessModel) }}
						</span>
					</el-form-item>
					<div class="flex">
						<el-form-item
							label-width="140px"
							:label="`下载APP入口开关:`"
							prop="appDownloadConfig"
						>
							<el-switch
								v-model="formData.appDownloadConfig"
								inline-prompt
								size="large"
								:active-value="1"
								:inactive-value="0"
							/>
						</el-form-item>
					</div>
				</el-form>
				<template #footer>
					<span>
						<el-button @click="visibleDialog = false">
							{{ $t('common.cancel') }}
						</el-button>
						<el-button type="primary" @click="handleSubmit">
							{{ $t('common.confirm') }}
						</el-button>
					</span>
				</template>
			</el-dialog>
			<el-dialog
				:visible.sync="allocationDialog"
				:title="
					businessModel === 1 ? '现金线默认配置' : '信用线默认配置'
				"
				:width="getWidth('500px')"
			>
				<el-form
					ref="allocationFormRef"
					:model="formData"
					:rules="editFormRules"
					label-width="auto"
					:close-on-click-modal="false"
				>
					<div class="flex">
						<el-form-item
							:label="`下载APP入口开关:`"
							prop="appDownloadConfig"
						>
							<el-switch
								v-model="formData.appDownloadConfig"
								inline-prompt
								size="large"
								:active-value="1"
								:inactive-value="0"
							/>
						</el-form-item>
					</div>
				</el-form>
				<template #footer>
					<span>
						<el-button @click="allocationDialog = false">
							{{ $t('common.cancel') }}
						</el-button>
						<el-button type="primary" @click="allocationSubmit">
							{{ $t('common.confirm') }}
						</el-button>
					</span>
				</template>
			</el-dialog>
		</main-content>
		<GoogleKeyInput
			:isShowdialog="isShowdialog"
			@getGoogleKey="getGoogleKey($event)"
			@backPrevStep="backPrevStep()"
		></GoogleKeyInput>
	</div>
</template>

<script>
import list from '@/mixins/list'
import { routerNames } from '@/utils/consts'
import BusinessModelSelector from './BusinessModelSelector.vue'
import MainContent from '@/components/MainContent/index.vue'
export default {
	name: routerNames.appDownloadConfigChannelConfig,
	components: {
		MainContent,
		BusinessModelSelector,
		GoogleKeyInput: () => import('@/components/GoogleKeyInput')
	},
	mixins: [list],
	data() {
		this.loadData = this.throttle(this.loadData, 1000)
		return {
			isShowdialog: false,
			ruleFormType: '',
			ruleFormValue: '',
			rowId: '',
			tableHeight: 480,
			businessModelRow: null,
			otherDependenComponents: [],
			queryData: {
				pageNum: 1,
				pageSize: 100,
				paymentMerchantType: 1,
				merchantId: null,
				userType: 0
			},
			type: true,
			businessModel: false,
			formData: {
				appDownloadConfig: '',

				businessModel: '2'
			},
			dataList: [],
			visibleDialog: false,
			allocationDialog: false,

			editFormRules: {
				proxyName: [
					{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}
				],
				merchantId: [
					{
						required: true,
						message: '请选择',
						trigger: ['blur', 'change']
					}
				],
				businessModel: [
					{
						required: true,
						message: '请选择',
						trigger: ['blur', 'change']
					}
				],
				creditLevel: [
					{
						required: true,
						message: '请选择',
						trigger: 'blur'
					}
				],
				appDownloadConfig: [
					{
						required: true,
						message: '请选择',
						trigger: 'blur'
					}
				]
			}
		}
	},
	computed: {
		payTypeList() {
			return this.globalDics.depositPaymentType || []
		}
	},
	mounted() {
		this.queryData.merchantId = this.$store.getters.userInfo.merchantId
		if (this.queryData.merchantId === '0') {
			this.queryData.merchantId = null
		}
	},
	methods: {
		mappingBusinessModels(key) {
			const BUSINESS_MODELS = [
				{ value: '0', label: '信用+现金模式' },
				{ value: '1', label: '现金模式' },
				{ value: '2', label: '信用模式' }
			]
			return BUSINESS_MODELS.find((item) => item?.value == key)?.label
		},
		getGoogleKey(data) {
			this.isShowdialog = false
			const loading = this.$loading({
				lock: true,
				text: 'Loading',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			})

			if (this.ruleFormType === 'add' || this.ruleFormType === 'edit') {
				const params = {
					merchantId: this.formData.merchantId,
					proxyName: this.formData.proxyName,
					appDownloadConfig: this.formData.appDownloadConfig,
					businessModel: this.formData.businessModel,
					haiyueAuthCode: data
				}
				if (this.ruleFormType === 'edit') {
					params.id = this.rowId
				}
				const apiName =
					this.ruleFormType === 'edit'
						? 'updateDownloadConfigUpdate'
						: 'addDownloadConfigList'
				this.$api[apiName](params)
					.then((res) => {
						if (res.code === 200) {
							this.$message.success(
								this.$t('common.modify_success')
							)
							this.reset()
							this.visibleDialog = false
						}
						loading.close()
					})
					.catch(() => {
						loading.close()
					})
			} else if (this.ruleFormType === 'del') {
				this.$api
					.deAppChannelConfig({
						id: this.rowId,
						haiyueAuthCode: data
					})
					.then(() => {
						this.loadData()
						this.$message({
							message: '删除成功',
							type: 'success'
						})
						loading.close()
					})
					.catch(() => {
						loading.close()
					})
			} else if (this.ruleFormType === 'allocation') {
				const params = {
					id: this.formData.id,
					appDownloadConfig: this.formData.appDownloadConfig,
					businessModel: this.businessModel,
					haiyueAuthCode: data
				}
				this.$api
					.updateDefaultConfig(params)
					.then((res) => {
						if (res.code === 200) {
							this.$message.success(
								this.$t('common.modify_success')
							)
							this.loadData()
							this.allocationDialog = false
						}
						loading.close()
					})
					.catch(() => {
						loading.close()
					})
			} else if (this.ruleFormType === 'appDownloadConfig') {
				this.$api
					.updateDownloadConfigUpdate({
						id: this.rowId,
						businessModel: Number(this.businessModelRow),
						[this.ruleFormType]: this.ruleFormValue,
						haiyueAuthCode: data
					})
					.then((res) => {
						if (res.code === 200) {
							this.$message.success(
								this.$t('common.modify_success')
							)
							this.loadData()
						}
						loading.close()
					})
					.catch(() => {
						loading.close()
					})
			}
		},
		backPrevStep() {
			this.isShowdialog = false
		},
		getBusinessModel() {
			const params = {
				merchantId: this.formData.merchantId,
				proxyName: this.formData.proxyName
			}
			this.$api
				.downloadConfigProxyVerify(params)
				.then((res) => {
					const {
						code,

						msg
					} = res
					if (code === 200) {
						this.formData.businessModel = String(
							res.data.businessModel
						)
						this.loadCreditLineConfig(res.data.businessModel)
					} else {
						this.$message({
							message: msg,
							type: 'error'
						})
						this.formData.businessModel = null
					}
				})
				.catch(() => {
					this.formData.businessModel = null
				})
		},
		cleanBlankSpace(key, key1) {
			if (this[key][key1]) {
				this[key][key1] = (this[key][key1] + '').replace(/\s+/g, '')
			}
		},
		search() {
			this.pageNum = 1
			this.queryData.pageNum = 1
			this.loadData()
		},
		loadData() {
			this.loading = true
			const params = {
				...this.queryData,
				...this.getParams(params)
			}
			for (const k in params) {
				if (params[k] === '' || params[k] === undefined) {
					delete params[k]
				}
			}
			this.$api
				.getDownloadConfigList(params)
				.then((res) => {
					this.loading = false
					const {
						code,
						data: { record, totalRecord },
						msg
					} = res
					if (code === 200) {
						this.dataList = record || [{}, {}]
						this.total = totalRecord || 0
					} else {
						this.loading = false
						this.$message({
							message: msg,
							type: 'error'
						})
					}
				})
				.catch(() => {
					this.loading = false
				})
		},
		reset() {
			this.queryData = {
				pageNum: 1,
				pageSize: 100,
				paymentMerchantType: 1,
				merchantId:
					this.$store.getters.userInfo.merchantId === '0'
						? null
						: this.$store.getters.userInfo.merchantId,
				userType: 0
			}
			this.pageNum = 1
			this.loadData()
		},
		updatedStatus(row, name) {
			this.rowId = row.id
			this.ruleFormType = name
			this.businessModelRow = row.businessModel
			this.ruleFormValue = row[name] == 0 ? 1 : 0
			this.isShowdialog = true
			// if (
			// 	this.ruleFormType === 'appDownloadConfig' ||
			// 	this.ruleFormType === 'memberWithdraw'
			// ) {
			// 	this.isShowdialog = true
			// } else {
			// 	const params = {
			// 		id: row.id
			// 	}
			// 	params[name] = row[name] == 0 ? 1 : 0
			// 	this.$api.updateDefaultConfig(params).then((res) => {
			// 		if (res.code === 200) {
			// 			this.$message.success(this.$t('common.modify_success'))
			// 			this.loadData()
			// 		}
			// 	})
			// }
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			this.$confirm(
				`<strong>是否删除该条配置?</strong></br><span style='font-size:12px;color:#c1c1c1'>${this.$t(
					'operation.warning_tips'
				)}</span>`,
				this.$t('common.success_tip'),
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning'
				}
			).then(() => {
				this.rowId = row.id
				this.ruleFormType = 'del'
				this.isShowdialog = true
			})
		},
		handleSizeChange(value) {
			this.pageNum = 1
			this.pageSize = value
			this.loadData()
		},
		handleCurrentChange(value) {
			this.pageNum = value
			this.loadData()
		},
		openEditDialog(row) {
			this.$refs.dialogFormRef && this.$refs.dialogFormRef.resetFields()
			this.ruleFormType = 'edit'
			this.rowId = row.id
			this.formData = Object.assign({}, row)
			this.visibleDialog = true
		},
		addFn() {
			this.$refs.dialogFormRef && this.$refs.dialogFormRef.resetFields()
			this.ruleFormType = 'add'
			this.formData = {
				businessModel: null,
				appDownloadConfig: 0
			}
			// this.loadCreditLineConfig(2)
			this.visibleDialog = true
		},
		loadCreditLineConfig(businessModel) {
			this.$api
				.getdefaultConfig({
					defaultConfig: 1,
					businessModel
				})
				.then((res) => {
					if (res.code === 200) {
						// this.allocationDialog = true
						// this.formData = res.data
						const { appDownloadConfig } = res.data
						this.formData.appDownloadConfig = appDownloadConfig
					}
				})
		},
		allocationFn(businessModel) {
			this.$refs.allocationFormRef &&
				this.$refs.allocationFormRef.resetFields()
			this.allocationDialog = true
			this.ruleFormType = 'allocation'
			this.businessModel = businessModel
			this.$api
				.getdefaultConfig({
					defaultConfig: 1,
					businessModel
				})
				.then((res) => {
					if (res.code === 200) {
						// this.allocationDialog = true
						this.formData = res.data
						this.formData.businessModel = String(
							this.formData.businessModel
						)
					}
				})
		},
		handleSubmit() {
			this.$refs.dialogFormRef.validate((valid) => {
				if (valid) {
					this.isShowdialog = true
				}
			})
		},
		allocationSubmit() {
			this.$refs.allocationFormRef.validate((valid) => {
				if (valid) {
					this.isShowdialog = true
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
	text-align: center;
	color: #909399;
	font-weight: 700;
}
::v-deep .caret-wrapper {
	position: absolute;
	top: 50%;
	transform: translateY(-50%);
}
.data-refresh {
	margin-top: 0;
	padding-bottom: 20px;
}
.look {
	//background-color: #00BFBF;
	//border-color: #00BFBF;
	color: #00bfbf;
}
</style>
